package com.ysx.server.controller.admin;

import com.github.pagehelper.Page;
import com.ysx.server.exception.BaseException;
import com.ysx.server.pojo.dto.UserDTO;
import com.ysx.server.pojo.dto.UserPageQueryDTO;
import com.ysx.server.pojo.entity.User;
import com.ysx.server.pojo.vo.PageQueryVO;
import com.ysx.server.pojo.vo.UserInfoVO;
import com.ysx.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/user")
@Slf4j
public class UserManageController {

    @Autowired
    private UserService userService;

    /**
     * 管理员获取用户信息 分页查询
     * @param userPageQueryDTO 查询条件
     * @return
     */
    @GetMapping("/userManage")
    public PageQueryVO<UserInfoVO> getUserManage(UserPageQueryDTO userPageQueryDTO){
        log.info("管理员获取用户信息:{}",userPageQueryDTO);
        Page<UserInfoVO> page = userService.getUserManage(userPageQueryDTO);
        long total = page.getTotal();
        List<UserInfoVO> result = page.getResult();
        return new PageQueryVO<UserInfoVO>(total,result);
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @PostMapping("/saveUser")
    public boolean save(@RequestBody User user){
        if(user==null){
            return false;
        }
        return userService.save(user);
    }

    /**
     * 更新用户信息
     * @param userDTO
     * @return
     */
    @PostMapping("/update")
    @CacheEvict(cacheNames = {"goodsCache_new","goodsCache_all","goodsCache","userManage"},allEntries=true)
    public boolean updateUser(@RequestBody UserDTO userDTO){
        log.info("修改用户信息：{}",userDTO);
        if(userDTO==null){
            return false;
        }
        return userService.update(userDTO);
    }

    /**
     * 删除用户
     * @param id 用户id
     * @return
     */
    @GetMapping("/delUser/{id}")
    @CacheEvict(cacheNames = "userManage",key = "#id")
    public boolean delUser(@PathVariable Long id){
        log.info("删除用户id：{}",id);
        if(id==1) {
            throw new BaseException("管理员用户禁止删除");
        }
        if(id==null||id<1) {
            return false;
        }
        return userService.delete(id);
    }
}
